<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { DeleteIndexact, GetAllDeta, PatchModifyType, PostCreateData, PutModifyData } from '@/api/modules/indexact.ts'

const ruleFormRef = ref<FormInstance>()

interface listType {
  list?: Record<string, any>
  iconList: Record<string, any>
  skinObj: Record<string, any>
  banner1Obj: Record<string, any>
  banner2Obj: Record<string, any>
  recommendObj: Record<string, any>
  transmitObj: Record<string, any>
  synopsisObj: Record<string, any>
  guidanceObj: Record<string, any>
}
const detaList = reactive<listType>({
  list: [],
  iconList: [],
  skinObj: {
    iconPic: '',
    linkUrl: '',
    iconType: 2,
    sort: 0,
  },
  banner1Obj: {
    iconPic: '',
    linkUrl: '',
    iconType: 3,
    sort: 0,
  },
  banner2Obj: {
    iconPic: '',
    linkUrl: '',
    iconType: 4,
    sort: 0,
  },
  recommendObj: {
    iconPic: '',
    linkUrl: '',
    iconType: 5,
    sort: 0,
  },
  transmitObj: {
    iconPic: '',
    linkUrl: '',
    iconType: 6,
    sort: 0,
  },
  synopsisObj: {
    iconPic: [],
    linkUrl: '',
    iconType: 7,
    sort: 0,
  },
  guidanceObj: {
    iconPic: '',
    linkUrl: '',
    iconType: 8,
    sort: 0,
  },
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string, index?: number) {
  if (key === 'iconList' && index !== undefined) {
    detaList.iconList[index].iconPic = url
  }
  else if (key === 'skinObj') {
    detaList.skinObj.iconPic = url
  }
  else if (key === 'banner1Obj') {
    detaList.banner1Obj.iconPic = url
  }
  else if (key === 'banner2Obj') {
    detaList.banner2Obj.iconPic = url
  }
  else if (key === 'recommendObj') {
    detaList.recommendObj.iconPic = url
  }
  else if (key === 'transmitObj') {
    detaList.transmitObj.iconPic = url
  }
  else if (key === 'guidanceObj') {
    detaList.guidanceObj.iconPic = url
  }
}

function AddCard(key: string) {
  if (key === 'iconList') {
    detaList.iconList.push({
      linkUrl: '',
      sort: 0,
      iconType: 1,
    })
  }
}

function AddIconCard(index: number) {
  detaList.iconList.splice(index + 1, 0, {
    linkUrl: '',
    sort: 0,
    iconType: 1,
  })
}
function DeleteIconCard(id: number, index: number, key: string) {
  ElMessageBox.confirm(
    '你确定要删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      if (id) {
        DeleteIndexact(id).then((res: any) => {
          if (res.statusCode === 200) {
            // eslint-disable-next-line ts/ban-ts-comment
            // @ts-expect-error
            detaList[key].splice(index, 1)
            ElMessage.success('删除成功')
          }
          else {
            ElMessage.error(`删除失败。${res.errors}`)
          }
        })
      }
      else {
        // eslint-disable-next-line ts/ban-ts-comment
        // @ts-expect-error
        detaList[key].splice(index, 1)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 提交
async function SubmitData() {
  const params = {
    ...detaList,
  }
  delete params.list

  // 使用 Object.entries 遍历 detaList 对象
  Object.entries(params).forEach(([key, value]) => {
    if (key === 'iconList') {
    // 如果是 iconList，遍历数组中的每个对象
      value.forEach((item: any) => {
        item.iconType = 1
        if (item.id) {
          const params = {
            ...item,
          }
          PutModifyData(params).then((res: any) => {
            if (res.statusCode !== 200) {
              ElMessage.error(`提交失败。${res.errors}`)
            }
          })
        }
        else {
          const params = {
            ...item,
          }
          PostCreateData(params).then((res: any) => {
            if (res.statusCode !== 200) {
              ElMessage.error(`提交失败。${res.errors}`)
            }
          })
        }
      })
    }
    else if (typeof value === 'object' && value !== null) {
      if (key === 'skinObj') {
        value.iconType = 2
      }
      else if (key === 'banner1Obj') {
        value.iconType = 3
      }
      else if (key === 'banner2Obj') {
        value.iconType = 4
      }
      else if (key === 'recommendObj') {
        value.iconType = 5
      }
      else if (key === 'transmitObj') {
        value.iconType = 6
      }
      else if (key === 'synopsisObj') {
        value.iconType = 7
      }
      else if (key === 'guidanceObj') {
        value.iconType = 8
      }
      if (value.id) {
        const params = {
          ...value,
        }
        if (value.iconType === 7) {
          params.iconPic = params.iconPic.join(',')
        }

        PutModifyData(params).then((res: any) => {
          if (res.statusCode !== 200) {
            ElMessage.error(`提交失败。${res.errors}`)
          }
        })
      }
      else {
        const params = {
          ...value,
        }
        if (value.iconType === 7) {
          params.iconPic = params.iconPic.join(',')
        }
        PostCreateData(params).then((res: any) => {
          if (res.statusCode !== 200) {
            ElMessage.error(`提交失败。${res.errors}`)
          }
        })
      }
    }
    else {
    // 其他情况（如数组或基本类型），直接打印
    }
  })
  ElMessage.success('提交成功')
}

onMounted(() => {
  GetAllDeta({ PageIndex: 1, PageSize: 100 }).then((res: any) => {
    if (res.statusCode === 200) {
      detaList.list = res.data.items
      detaList.list!.forEach((item: any) => {
        if (item.iconType === 1) {
          detaList.iconList.push(item)
        }
        else if (item.iconType === 2) {
          detaList.skinObj = item
        }
        else if (item.iconType === 3) {
          detaList.banner1Obj = item
        }
        else if (item.iconType === 4) {
          detaList.banner2Obj = item
        }
        else if (item.iconType === 5) {
          detaList.recommendObj = item
        }
        else if (item.iconType === 6) {
          detaList.transmitObj = item
        }
        else if (item.iconType === 7) {
          detaList.synopsisObj = item
          detaList.synopsisObj.iconPic = detaList.synopsisObj.iconPic.split(',')
        }
        else if (item.iconType === 8) {
          detaList.guidanceObj = item
        }
      })
    }
    else {
      ElMessage.error(`获取信息失败。${res.errors}`)
    }
  })
})
</script>

<template>
  <div>
    <PageHeader title="首页活动" />
    <ElForm ref="ruleFormRef" :model="detaList.list" label-width="auto">
      <PageMain title="活动图标">
        <ElRow :gutter="20">
          <el-button v-if="detaList.iconList?.length === 0" type="primary" @click="AddCard('iconList')">
            添加
          </el-button>
          <ElCol v-for="(item, index) in detaList.iconList" :key="item.id" :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="item.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!item.id"
                  @change="PatchModifyType({ id: item.id, enable: item.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="item.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="自定义排序（升序）">
                <el-input v-model="item.sort" placeholder="请输入自定义排序" type="number" />
              </ElFormItem>
              <ElFormItem label="上传图标">
                <ImageUpload
                  height="200" width="auto" :size="1"
                  :url="item.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'iconList', Number(index))"
                />
              </ElFormItem>
              <template #footer>
                <div class="text-right">
                  <el-button type="success" :disabled="detaList.iconList.length > 4" @click="AddIconCard(Number(index))">
                    添加
                  </el-button>
                  <el-button type="danger" @click="DeleteIconCard(item.id, Number(index), 'iconList')">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="商品推广">
        <ElRow :gutter="20">
          <ElCol :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <template #header>
                <span>好友引导</span>
              </template>
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="detaList.guidanceObj.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!detaList.guidanceObj.id"
                  @change="PatchModifyType({ id: detaList.guidanceObj.id, enable: detaList.guidanceObj.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="detaList.guidanceObj.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="图片上传">
                <ImageUpload
                  height="150" width="auto" :size="5"
                  :url="detaList.guidanceObj.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'guidanceObj')"
                />
              </ElFormItem>
            </el-card>
          </ElCol>
          <ElCol :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <template #header>
                <span>肌肤检测</span>
              </template>
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="detaList.skinObj.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!detaList.skinObj.id"
                  @change="PatchModifyType({ id: detaList.skinObj.id, enable: detaList.skinObj.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="detaList.skinObj.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="图片上传">
                <ImageUpload
                  height="150" width="auto" :size="5"
                  :url="detaList.skinObj.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'skinObj')"
                />
              </ElFormItem>
            </el-card>
          </ElCol>
          <ElCol :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <template #header>
                <span>商品Banner1</span>
              </template>
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="detaList.banner1Obj.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!detaList.banner1Obj.id"
                  @change="PatchModifyType({ id: detaList.banner1Obj.id, enable: detaList.banner1Obj.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="detaList.banner1Obj.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="图片上传">
                <ImageUpload
                  height="150" width="auto" :size="5"
                  :url="detaList.banner1Obj.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'banner1Obj')"
                />
              </ElFormItem>
            </el-card>
          </ElCol>
          <ElCol :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <template #header>
                <span>商品Banner2</span>
              </template>
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="detaList.banner2Obj.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!detaList.banner2Obj.id"
                  @change="PatchModifyType({ id: detaList.banner2Obj.id, enable: detaList.banner2Obj.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="detaList.banner2Obj.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="图片上传">
                <ImageUpload
                  height="150" width="auto" :size="5"
                  :url="detaList.banner2Obj.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'banner2Obj')"
                />
              </ElFormItem>
            </el-card>
          </ElCol>
          <ElCol :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <template #header>
                <span>新品推荐</span>
              </template>
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="detaList.recommendObj.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!detaList.recommendObj.id"
                  @change="PatchModifyType({ id: detaList.recommendObj.id, enable: detaList.recommendObj.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="detaList.recommendObj.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="图片上传">
                <ImageUpload
                  height="150" width="auto" :size="5"
                  :url="detaList.recommendObj.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'recommendObj')"
                />
              </ElFormItem>
            </el-card>
          </ElCol>
          <ElCol :md="8" class="mb-5" style="min-width: 200px;">
            <el-card shadow="hover">
              <template #header>
                <span>新品速递</span>
              </template>
              <ElFormItem label="是否启用">
                <el-switch
                  v-model="detaList.transmitObj.enable"
                  active-text="启用"
                  inactive-text="未启用"
                  :disabled="!detaList.transmitObj.id"
                  @change="PatchModifyType({ id: detaList.transmitObj.id, enable: detaList.transmitObj.enable })"
                />
              </ElFormItem>
              <ElFormItem label="跳转地址">
                <el-input v-model="detaList.transmitObj.linkUrl" placeholder="请输入跳转地址" />
              </ElFormItem>
              <ElFormItem label="图片上传">
                <ImageUpload
                  height="150" width="auto" :size="5"
                  :url="detaList.transmitObj.iconPic" @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'transmitObj')"
                />
              </ElFormItem>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="集团简介">
        <ElRow :gutter="20">
          <ElCol :md="24" class="mb-5" style="min-width: 200px;">
            <ImagesUpload
              :size="5" :url="(detaList.synopsisObj.iconPic as string[])" :max="1" :ext="['jpg', 'png']"
            />
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 90px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style scoped>
/* stylelint-disable-next-line no-empty-source */
</style>
